import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import { User } from '../types';
import apiClient from '../utils/api';

export const useAuthStore = defineStore('auth', () => {
  const user = ref<User | null>(null);
  const token = ref<string | null>(null);
  const isLoading = ref(false);
  const error = ref<string | null>(null);

  // 计算属性
  const isAuthenticated = computed(() => !!token.value && !!user.value);
  const username = computed(() => user.value?.username || '');

  // 初始化认证状态
  const initAuth = () => {
    const savedToken = localStorage.getItem('token');
    if (savedToken) {
      token.value = savedToken;
      apiClient.setToken(savedToken);
      
      // 对于模拟token，直接解析用户信息
      try {
        const tokenData = JSON.parse(atob(savedToken));
        user.value = {
          username: tokenData.sub,
          email: '',
          is_active: true,
          created_at: new Date().toISOString(),
          id: 1
        };
      } catch (err) {
        // 如果token解析失败，清除无效token
        logout();
      }
    }
  };

  // 获取当前用户信息
  const fetchCurrentUser = async () => {
    try {
      isLoading.value = true;
      error.value = null;
      const userData = await apiClient.getCurrentUser();
      user.value = userData;
    } catch (err) {
      error.value = '获取用户信息失败';
      logout();
    } finally {
      isLoading.value = false;
    }
  };

  // 登录
  const login = async (username: string, password: string) => {
    try {
      isLoading.value = true;
      error.value = null;
      
      // 模拟登录延迟
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      // 简单的验证逻辑 - 只允许特定用户名密码登录
      // 在实际项目中这里会调用真实的API进行验证
      if (username === 'admin' && password === '123456') {
        // 登录成功，创建模拟token
        const mockToken = btoa(JSON.stringify({ sub: username, exp: Date.now() + 86400000 }));
        token.value = mockToken;
        localStorage.setItem('token', mockToken);
        apiClient.setToken(mockToken);
        
        // 设置用户信息
        user.value = {
          username: username,
          email: '',
          is_active: true,
          created_at: new Date().toISOString(),
          id: 1
        };
        
        return true;
      } else {
        // 登录失败
        throw new Error('用户名或密码错误');
      }
    } catch (err: any) {
      // 确保错误信息正确设置并保持显示
      if (err.message) {
        error.value = err.message;
      } else if (err.response?.data?.detail) {
        error.value = err.response.data.detail;
      } else {
        error.value = '登录失败，请检查用户名和密码';
      }
      return false;
    } finally {
      isLoading.value = false;
    }
  };

  // 注册
  const register = async (username: string, email: string, password: string) => {
    try {
      isLoading.value = true;
      error.value = null;
      
      const response = await apiClient.register({ username, email, password });
      token.value = response.access_token;
      user.value = response.user;
      
      return true;
    } catch (err: any) {
      error.value = err.response?.data?.detail || '注册失败';
      return false;
    } finally {
      isLoading.value = false;
    }
  };

  // 登出
  const logout = () => {
    user.value = null;
    token.value = null;
    error.value = null;
    apiClient.setToken(null);
  };

  // 清除错误
  const clearError = () => {
    error.value = null;
  };

  return {
    user,
    token,
    isLoading,
    error,
    isAuthenticated,
    username,
    initAuth,
    login,
    register,
    logout,
    clearError,
    fetchCurrentUser,
  };
});